
import * as struct from "./struct";
import { oa, ns } from "./itf";
import { Where } from "./struct";


export function clearEscapeChar(p: any): string {
  if (p) {
    if (typeof p != "string") p = JSON.stringify(p);
    return p.replace(/\\/g, "\\\\").replace(/'/g, "\\'").toString();
  } else if (typeof p == "number") return "0";
  return "";
};

export function methodMerge(p: struct.Where, nc = false) {
  let ret: string = p.logic ? `${p.logic} ` : " ";
  ret += "`" + p.field + "`" + p.method;
  let t: string = nc ? p.value.toString() : clearEscapeChar(p.value);
  if (p.type.length == 2) {
    if (t.length > p.type[0]) {
      t = p.type[1] ? t.substr(0, p.type[1]) : t.substr(t.length - p.type[1]);
    }
    t = `'${t}'`;
  }
  ret += t;
  return ret;
}
export function methodIn(p: struct.Where, not: any = false) {
  let r: string = "";
  if (Array.isArray(p.value)) {
    const d: ns[] = [];
    p.value.forEach(a => {
      switch (typeof a) {
        case "number":
          d.push(a);
          break;
        case "string":
          d.push(clearEscapeChar(a));
          break;
        default:
          break;
      }
    });
    p.value = d;
    r = `${p.logic || ""} \`${p.field}\` ${not ? "not " : ""}in (${p.value.join()})`;
  }
  return r;
}


